/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.wizards.core.events.investiture;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.JXDatePicker;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.WizardDescriptor;
import org.openide.util.Lookup;
import pt.iasd.youthshelter.datamodel.Club;
import pt.iasd.youthshelter.datamodel.Honor;
import pt.iasd.youthshelter.datamodel.Investiture;
import pt.iasd.youthshelter.datamodel.Lider;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import pt.iasd.youthshelter.datamodel.ProgressiveClass;
import pt.iasd.youthshelter.datamodel.service.InvestitureController;
import pt.iasd.youthshelter.wizards.core.WizardKeys;

public final class InvestitureVisualPanel extends JPanel implements DocumentListener, ActionListener {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle");
    /* Logging object. */
    private final Logger logger = Logger.getLogger(this.getClass().getName());
    
    private List<Pathfinder> pathfinders;
    
    private List<Investiture> investitures;
    
    private Set<Investiture> editedInvestitures = new HashSet<>();
    
    private Set<Investiture> removedInvestitures = new HashSet<>();

    /**
     * Creates new form InvestitureVisualPanel
     */
    public InvestitureVisualPanel() {
        this(null, null);
    }
    
    /**
     * Creates new form InvestitureVisualPanel
     */
    public InvestitureVisualPanel(String place, Date date) {
        if(place != null && !place.isEmpty() && date != null) {
            investitures = loadInvestitureTableData(place, date);
            extractPathfinderList();
            initComponents();
            this.PlaceTextField.setText(place);
            this.EventDatePicker.setDate(date);
            firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
        } else {
            investitures = new ArrayList<>();
            initComponents();
        }
    }

    @Override
    public String getName() {
        return WizardKeys.PROP_INVESTITURE_STEPS[0];
    }

    public List<Investiture> getInvestitures() {
        return investitures;
    }

    public Set<Investiture> getEditedInvestitures() {
        return editedInvestitures;
    }

    public Set<Investiture> getRemovedInvestitures() {
        return removedInvestitures;
    }

    public JXDatePicker getEventDatePicker() {
        return EventDatePicker;
    }

    public JTextField getPlaceTextField() {
        return PlaceTextField;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PlaceLabel = new javax.swing.JLabel();
        PlaceTextField = new javax.swing.JTextField();
        DateLabel = new javax.swing.JLabel();
        EventDatePicker = new org.jdesktop.swingx.JXDatePicker();
        TableScrollPane = new javax.swing.JScrollPane();
        DetailsTable = new javax.swing.JTable();
        AddButton = new javax.swing.JButton();
        EditButton = new javax.swing.JButton();
        RemoveButton = new javax.swing.JButton();

        org.openide.awt.Mnemonics.setLocalizedText(PlaceLabel, bundle.getString("InvestitureVisualPanel.PlaceLabel.text"));

        PlaceTextField.getDocument().addDocumentListener(this);

        org.openide.awt.Mnemonics.setLocalizedText(DateLabel, bundle.getString("InvestitureVisualPanel.DateLabel.text"));

        EventDatePicker.setMaximumSize(new java.awt.Dimension(150, 22));
        EventDatePicker.setMinimumSize(new java.awt.Dimension(150, 22));
        EventDatePicker.setPreferredSize(new java.awt.Dimension(150, 22));
        EventDatePicker.addActionListener(this);

        DetailsTable.setModel(buildTableModel());
        DetailsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                DetailsTableMousePressed(evt);
            }
        });
        TableScrollPane.setViewportView(DetailsTable);

        org.openide.awt.Mnemonics.setLocalizedText(AddButton, bundle.getString("Buttons.Add"));
        AddButton.setMaximumSize(new java.awt.Dimension(100, 23));
        AddButton.setMinimumSize(new java.awt.Dimension(100, 23));
        AddButton.setPreferredSize(new java.awt.Dimension(100, 23));
        AddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(EditButton, bundle.getString("Buttons.Edit"));
        EditButton.setEnabled(false);
        EditButton.setMaximumSize(new java.awt.Dimension(100, 23));
        EditButton.setMinimumSize(new java.awt.Dimension(100, 23));
        EditButton.setPreferredSize(new java.awt.Dimension(100, 23));
        EditButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(RemoveButton, bundle.getString("Buttons.Remove"));
        RemoveButton.setEnabled(false);
        RemoveButton.setMaximumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setMinimumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setPreferredSize(new java.awt.Dimension(100, 23));
        RemoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(PlaceLabel)
                            .addComponent(DateLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(PlaceTextField)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(EventDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(TableScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(EditButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PlaceLabel)
                    .addComponent(PlaceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(DateLabel)
                    .addComponent(EventDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(TableScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(EditButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<>();
        panels.add(new AddInvestitureDetailsWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("InvestitureDetails.Title.Add"));
        if(pathfinders != null && !pathfinders.isEmpty()) {
            wiz.putProperty(WizardKeys.PROP_PATHFINDER_LIST, pathfinders);
        }
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            Pathfinder pathfinder = (Pathfinder)wiz.getProperty(WizardKeys.PROP_PATHFINDER);
            Lider lider = (Lider)wiz.getProperty(WizardKeys.PROP_LIDER);
            Club club = (Club)wiz.getProperty(WizardKeys.PROP_CLUB);
            ProgressiveClass pClass = (ProgressiveClass)wiz.getProperty(WizardKeys.PROP_PCLASS);
            List<Honor> honors = (List<Honor>)wiz.getProperty(WizardKeys.PROP_HONOR_LIST);
            Investiture investiture = new Investiture();
            investiture.setPathfinderId(pathfinder);
            investiture.setLiderId(lider);
            if(club != null) {
                List<Club> clubs = new ArrayList<>();
                clubs.add(club);
                investiture.setClubList(clubs);
            }
            if(pClass != null) {
                List<ProgressiveClass> classes = new ArrayList<>();
                classes.add(pClass);
                investiture.setProgressiveClassList(classes);
            }
            if(honors != null && !honors.isEmpty()) {
                investiture.setHonorList(honors);
            }
            investitures.add(investiture);
            setTable();
        }
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }//GEN-LAST:event_AddButtonActionPerformed

    private void EditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditButtonActionPerformed
        int selectedRow = DetailsTable.getSelectedRow();
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<>();
        panels.add(new EditInvestitureDetailsWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("InvestitureDetails.Title.Edit"));
        Investiture investiture = investitures.get(selectedRow);
        wiz.putProperty(WizardKeys.PROP_PATHFINDER, investiture.getPathfinderId());
        wiz.putProperty(WizardKeys.PROP_LIDER, investiture.getLiderId());
        List<Club> clubs = investiture.getClubList();
        if(clubs != null && !clubs.isEmpty()) {
            wiz.putProperty(WizardKeys.PROP_CLUB, clubs.get(0));
        }
        List<ProgressiveClass> classes = investiture.getProgressiveClassList();
        if(classes != null && !classes.isEmpty()) {
            wiz.putProperty(WizardKeys.PROP_PCLASS, classes.get(0));
        }
        List<Honor> honors = investiture.getHonorList();
        if(honors != null && !honors.isEmpty()) {
            wiz.putProperty(WizardKeys.PROP_HONOR_LIST, honors);
        }
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            Club club = (Club)wiz.getProperty(WizardKeys.PROP_CLUB);
            ProgressiveClass pClass = (ProgressiveClass)wiz.getProperty(WizardKeys.PROP_PCLASS);
            honors = (List<Honor>)wiz.getProperty(WizardKeys.PROP_HONOR_LIST);
            if(club != null) {
                clubs = new ArrayList<>();
                clubs.add(club);
                investiture.setClubList(clubs);
            }
            if(pClass != null) {
                classes = new ArrayList<>();
                classes.add(pClass);
                investiture.setProgressiveClassList(classes);
            }
            if(honors != null && !honors.isEmpty()) {
                investiture.setHonorList(honors);
            }
            if(investiture.getId() != null) {
                editedInvestitures.add(investiture);
            }
            setTable();
        }
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }//GEN-LAST:event_EditButtonActionPerformed

    private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButtonActionPerformed
        int selectedRow = DetailsTable.getSelectedRow();
        NotifyDescriptor dialog = new NotifyDescriptor(
            String.format(bundle.getString("InvestitureDetails.Confirmation.Remove"),
                investitures.get(selectedRow).getPathfinderId().getName()),
            bundle.getString("InvestitureDetails.Title.Remove"), NotifyDescriptor.OK_CANCEL_OPTION,
            NotifyDescriptor.WARNING_MESSAGE, null, null);
        if(DialogDisplayer.getDefault().notify(dialog) == DialogDescriptor.OK_OPTION) {
            if(investitures.get(selectedRow).getPathfinderId().getId() != null) {
                int pathfinderId = investitures.get(selectedRow).getPathfinderId().getId();
                removedInvestitures.add(getInvestitureByPathfinder(pathfinderId));
                removePathfinderFromList(pathfinderId);
            }
            investitures.remove(selectedRow);
            setTable();
        }
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }//GEN-LAST:event_RemoveButtonActionPerformed

    private void DetailsTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_DetailsTableMousePressed
        int selectedRow = DetailsTable.getSelectedRow();
        if(selectedRow != -1) {
            EditButton.setEnabled(true);
            RemoveButton.setEnabled(true);
        } else {
            EditButton.setEnabled(false);
            RemoveButton.setEnabled(false);
        }
    }//GEN-LAST:event_DetailsTableMousePressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddButton;
    private javax.swing.JLabel DateLabel;
    private javax.swing.JTable DetailsTable;
    private javax.swing.JButton EditButton;
    private org.jdesktop.swingx.JXDatePicker EventDatePicker;
    private javax.swing.JLabel PlaceLabel;
    private javax.swing.JTextField PlaceTextField;
    private javax.swing.JButton RemoveButton;
    private javax.swing.JScrollPane TableScrollPane;
    // End of variables declaration//GEN-END:variables

    // <editor-fold defaultstate="collapsed" desc="Table Data Code">
    private List<Investiture> loadInvestitureTableData(String place, Date date) {
        InvestitureController controller = Lookup.getDefault().lookup(InvestitureController.class);
        if(controller != null) {
            try{
                return controller.findInvestitureEntitiesByPlaceAndDate(place, date);
            } catch(Exception ex) {
                logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            }
        }
        return null;
    }
    
    private DefaultTableModel buildTableModel(){
        Object[][] data;
        String[] headers = new String[]{
            java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle")
                    .getString("TableHeaders.Id"),
            java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle")
                    .getString("TableHeaders.Pathfinder"),
            java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle")
                    .getString("TableHeaders.Lider"),
            java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle")
                    .getString("TableHeaders.Club"),
            java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle")
                    .getString("TableHeaders.ProgressiveClass"),
            java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle")
                    .getString("TableHeaders.Honors")};
        if(investitures == null || investitures.isEmpty()) {
            data = new Object[][]{};
        } else {
            data = new Object[investitures.size()][Investiture.class.getDeclaredFields().length - 3];
            int i = 0;
            for(Investiture investiture : investitures) {
                data[i][0] = investiture.getId();
                data[i][1] = investiture.getPathfinderId().getName();
                data[i][2] = investiture.getLiderId().getName();
                List<Club> clubs = investiture.getClubList();
                data[i][3] = (clubs != null && !clubs.isEmpty());
                List<ProgressiveClass> classes = investiture.getProgressiveClassList();
                data[i][4] = (classes != null && !classes.isEmpty());
                List<Honor> honors = investiture.getHonorList();
                data[i][5] = (honors == null)? 0 : honors.size();
                ++i;
            }
        }
        DefaultTableModel tablemodel = new DefaultTableModel(data, headers){
            Class[] types = new Class[]{java.lang.Integer.class, java.lang.String.class, java.lang.String.class,
                java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Integer.class};
            boolean[] canEdit = new boolean[]{false, false, false, false, false, false};

            @Override
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };
        return tablemodel;
    }
    
    private void setTable() {
        DetailsTable.setModel(buildTableModel());
        DetailsTable.removeColumn(DetailsTable.getColumn(DetailsTable.getColumnName(0)));
        EditButton.setEnabled(false);
        RemoveButton.setEnabled(false);
    }// </editor-fold>

    @Override
    public void insertUpdate(DocumentEvent e) {
        changedUpdate(e);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        changedUpdate(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }
    
    // <editor-fold defaultstate="collapsed" desc="Details Lists Code">
    private Investiture getInvestitureByPathfinder(int pathfinderId) {
        for(Investiture investiture : investitures) {
            if(investiture.getPathfinderId().getId() == pathfinderId) {
                return investiture;
            }
        }
        return null;
    }

    private void extractPathfinderList() {
        pathfinders = new ArrayList<>();
        for(Investiture investiture : investitures) {
            if(!pathfinders.contains(investiture.getPathfinderId())) {
                pathfinders.add(investiture.getPathfinderId());
            }
        }
    }

    private void removePathfinderFromList(int pathfinderId) {
        if(pathfinders != null && !pathfinders.isEmpty()) {
            for(Pathfinder pathfinder : pathfinders) {
                if(pathfinder.getId() == pathfinderId) {
                    pathfinders.remove(pathfinder);
                    return;
                }
            }
        }
    }// </editor-fold>

    @Override
    public void actionPerformed(ActionEvent e) {
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }
}
